<?php

namespace App\Rep;

use App\Models\MaterialBill;
use App\Models\MaterialBillChild;
use App\Models\ProductMaterial;
use Illuminate\Support\Facades\DB;

class MaterialBillRep
{

    public function getMaterialBillListRep($params){

        return MaterialBill::Search($params)->with(['child'=>function($q){
            $q->with(['material']);
        },'warehouse','model_number','specification','color','product'=>function($q){
            $q->select('product.id','product.product_name');
        }])
            ->orderBy('id','desc')
            ->paginate($params['per_page']??100);
    }

    public function createMaterialBillRep($params){
        DB::beginTransaction();
        try {
            if(isset($params['id']) && !empty($params['id'])){
                $model = MaterialBill::find($params['id']);
                $model->name = $params['name'];
                $model->amount_total = $params['amount_total'];
                $model->product_id = $params['product_id'];
                $model->model_number_id = $params['model_number_id'];
                $model->specification_id = $params['specification_id'];
                $model->color_id = $params['color_id'];
                $model->save();
                $bill_id = $params['id'];
                MaterialBillChild::where('bill_id',$bill_id)->delete();
            }else{
                $bill_id = MaterialBill::insertGetId(['name'=>$params['name'],
                    'product_id'=>$params['product_id'],
                    'model_number_id'=>$params['model_number_id'],
                    'specification_id'=>$params['specification_id'],
                    'color_id'=>$params['color_id'],
                ]);
            }
            $dosage_arr = $params['dosage_arr'];
            foreach($dosage_arr as $k=>$v){
                $where = [
                    'bill_id'=>$bill_id,
                    'material_id'=>$v['material_id'],
                ];
                $obj = MaterialBillChild::updateOrCreate($where,[$where,'dosage'=>$v['dosage']]);
            }

            DB::commit();
            return ['code'=>0,'data'=>[],'msg'=>'success'];
        }catch (\Exception $exception){
            DB::rollBack();
            return ['code'=>2001,'data'=>[],'msg'=>$exception->getMessage()];
        }
    }

    public function updateMaterialBillChildRep($params){
        $model = MaterialBillChild::find($params['bill_child_id']);
        $model->dosage = $params['dosage'];
        $model->save();
        return $model;
    }

    public function delMaterialBillChildRep($params){
        $model = MaterialBillChild::where('id',$params['bill_child_id'])->delete();
        return $model;
    }


}
